<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商家名称" prop="merName">
        <el-input
            v-model="queryParams.merName"
            placeholder="请输入商家名称"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>

      <el-form-item label="上架状态" prop="publishStatus">
        <el-select v-model="queryParams.publishStatus" placeholder="请选择上架状态" clearable>
          <el-option
              v-for="dict in tprod_publish_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="套餐名称" prop="prodName">
        <el-input
            v-model="queryParams.prodName"
            placeholder="请输入套餐名称"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
<!--      <el-form-item label="套餐目录" prop="prodCatalogId">-->
<!--        <el-select v-model="queryParams.prodCatalogId" placeholder="请选择套餐目录" clearable>-->
<!--          <el-option-->
<!--              v-for="dict in shop_type"-->
<!--              :key="dict.value"-->
<!--              :label="dict.label"-->
<!--              :value="dict.value"-->
<!--          />-->
<!--        </el-select>-->
<!--      </el-form-item>-->
      <el-form-item label="最小价格" prop="minimumPrice">
        <el-row>
          <el-col :span="11">
            <el-input-number v-model="queryParams.minimumPrice" :controls="false" :precision="2"
                             placeholder="最小价格"></el-input-number>
          </el-col>


        </el-row>
      </el-form-item>
      <!-- <el-col :span="2" style="display: inline-block;">-</el-col> -->
      <el-form-item label="最大价格" prop="maximumPrice">
        <el-row>

          <el-col :span="11">
            <el-input-number v-model="queryParams.maximumPrice" :controls="false" :precision="2"
                             placeholder="最大价格"></el-input-number>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['system:tprod:add']"
            :class="{'but-disabled': userStore.isRead === 1}"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['system:tprod:remove']"
            :class="{'but-disabled': userStore.isRead === 1}"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['system:tprod:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="tprodList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="商家名称" align="center" prop="merName">
        <template #default="scope">
          <span style="color:red;" v-if="scope.row.merStatus =='04'">{{ scope.row.merName }}</span>
          <span v-else>{{ scope.row.merName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="套餐名称" align="center" prop="prodName"/>
<!--      <el-table-column label="套餐目录" align="center" prop="prodCatalogId">-->
<!--        <template #default="scope">-->
<!--          <dict-tag :options="shop_type" :value="scope.row.prodCatalogId"/>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column label="上架状态" align="center" prop="publishCount">
        <template #default="scope">
          <span v-if="scope.row.publishCount === 0">未上架</span>
          <span v-if="scope.row.publishCount > 0">已上架({{ scope.row.publishCount }})</span>
        </template>
      </el-table-column>
      <el-table-column label="销售时间" align="center" prop="saleStartTime" width="190">
        <template #default="scope">
          <span>{{
              parseTime(scope.row.saleStartTime, '{y}-{m}-{d}')
            }}至{{ parseTime(scope.row.saleEndTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="有效期" align="center" prop="effTime">
        <template #default="scope">
          <!-- <dict-tag :options="effective_time" :value="scope.row.effTime"/> -->
          <span v-if="scope.row.effTime > 0">{{ scope.row.effTime }}天</span>
          <span v-else>长期</span>
        </template>
      </el-table-column>
      <el-table-column label="原价" align="center" prop="origPrice"/>
      <el-table-column label="售价" align="center" prop="salePrice"/>
      <el-table-column label="限购次数" align="center" prop="limitTimes"/>
      <el-table-column label="库存数量" align="center" prop="store"/>
      <el-table-column label="已售数量" align="center" prop="sold"/>
      <el-table-column label="预约信息" width="150" align="center" prop="reserveInfo">
        <!-- <template #default="scope">
          <dict-tag :options="package_reserve_info" :value="scope.row.reserveInfo"/>
        </template> -->
      </el-table-column>
      <el-table-column label="使用时间" width="150" align="center" prop="serviceTime">
        <!-- <template #default="scope">
          <dict-tag :options="package_service_time" :value="scope.row.serviceTime"/>
        </template> -->
      </el-table-column>
      <el-table-column label="操作" align="center" width="250" class-name="small-padding fixed-width" fixed="right">
        <template #default="scope">
          <el-button link type="primary" icon="View" @click="handleView(scope.row, scope.index)"
                     v-hasPermi="['system:tprod:query']">查看
          </el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                     :class="{'but-disabled': userStore.isRead === 1 || (userStore.isRead === 0 && !(scope.row.merStatus === '02'))}"
                     v-hasPermi="['system:tprod:edit']">修改
          </el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                     :class="{'but-disabled': userStore.isRead === 1 || (userStore.isRead === 0 && !(scope.row.merStatus === '02' && scope.row.publishCount === 0))}"
                     v-hasPermi="['system:tprod:remove']">删除
          </el-button>
          <el-button link type="primary" icon="Wallet" @click="handlePrice(scope.row)"
                     :class="{'but-disabled': userStore.isRead === 1 || (userStore.isRead === 0 && !(scope.row.merStatus === '02' && scope.row.isFree === 0))}"
                     v-hasPermi="['system:tprod:price']">定价
          </el-button>
          <el-button link type="primary" icon="Finished" @click="handlePublish(scope.row)"
                     :class="{'but-disabled': userStore.isRead === 1 || (userStore.isRead === 0 && !(scope.row.merStatus === '02'))}"
                     v-hasPermi="['system:tprod:publish']">发布
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改套餐列表对话框 -->
    <el-dialog :title="title" v-model="open" width="1000px" append-to-body>
      <el-form ref="tprodRef" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="商家名称" prop="merId" v-if="disableNum===0">
              <mer-select :key="refreshTime" v-model="form.merId" :typeList=[1,2]
                          :disabledValue="disableNum"></mer-select>
            </el-form-item>
            <el-form-item label="商家名称" v-if="disableNum===1">
              {{ form.merName }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="套餐名称" prop="prodName">
              <el-input v-model="form.prodName" placeholder="请输入套餐名称"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="主图" prop="prodMainPic">
              <image-upload v-model="form.prodMainPic" :limit="1"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="详情图" prop="prodDetailPic" >
              <image-upload v-model="form.prodDetailPic" :limit="9"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
<!--          <el-col :span="12">-->
<!--            <el-form-item label="套餐目录" prop="prodCatalogId">-->
<!--              <el-select v-model="form.prodCatalogId" placeholder="请选择套餐目录">-->
<!--                <el-option-->
<!--                    v-for="dict in shop_type"-->
<!--                    :key="dict.value"-->
<!--                    :label="dict.label"-->
<!--                    :value="parseInt(dict.value)"-->
<!--                ></el-option>-->
<!--              </el-select>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
          <el-col :span="12">
            <el-tooltip content="不填则默认长期有效" placement="top-start">
              <el-form-item label="有效期" prop="effTime">
                <el-input-number v-model="form.effTime" :max="999999" :min="0" value-on-clear="1"/>
                <!-- <el-select v-model="form.effTime" placeholder="请选择有效期" clearable>
                  <el-option
                      v-for="dict in effective_time"
                      :key="dict.value"
                      :label="dict.label"
                      :value="parseInt(dict.value)"
                  />
                </el-select> -->
              </el-form-item>
            </el-tooltip>
          </el-col>
          <el-col :span="12">
            <el-tooltip content="仅在此时间段内店铺“上架”的商品，小程序中可见" placement="top-start">
              
              <el-form-item label="销售时间" prop="saleStartTime">
                <el-date-picker
                    :clearable="false"
                    v-model="saleTimeRange"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    value-format="YYYY-MM-DD"
                    @change="handleSaleTimeChange"
                ></el-date-picker>
              </el-form-item>
            </el-tooltip>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="原价" prop="origPrice">
              <el-input-number v-model="form.origPrice" :max="999999" :min="0.01" :precision="2"/>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="售价" prop="price">
              <el-input-number v-model="form.price" :max="999999" :min="0.01" :precision="2"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-tooltip content="表示同一用户可以购买此套餐的数量" placement="top-start">
              <el-form-item label="限购次数" prop="limitTimes">
              
                <el-input-number v-model="form.limitTimes" :max="999999" :min="1" step-strictly/>
              </el-form-item>
            </el-tooltip>
          </el-col>
          <el-col :span="12">
            <el-form-item label="库存数量" prop="store">
              <!-- <el-input v-model="form.store" placeholder="请输入库存数量"  type="number"/> -->
              <el-input-number v-model="form.store" :max="999999" :min="1" step-strictly/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="适用人数" prop="maxPeoples">
              <!-- <el-input v-model="form.maxPeoples" placeholder="请输入适用人数"/> -->
              <el-input-number v-model="form.maxPeoples" :max="999999" :min="1" step-strictly :value-on-clear="1"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="预约信息" prop="reserveInfo">
              <el-input v-model="form.reserveInfo" placeholder="请输入预约信息" @blur="changeReserveInfo"/>
              <!-- <el-select v-model="form.reserveInfo" placeholder="请选择预约信息">
                <el-option
                    v-for="dict in package_reserve_info"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                ></el-option>
              </el-select> -->
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="使用时间" prop="serviceTime">
              <el-input v-model="form.serviceTime" placeholder="请输入使用时间" @blur="changeServiceTime"/>
              <!-- <el-select v-model="form.serviceTime" placeholder="请选择使用时间">
                <el-option
                    v-for="dict in package_service_time"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                ></el-option>
              </el-select> -->
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="描述" prop="prodDesc">
              <editor v-model="form.prodDesc" :min-height="192"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看商家详情 -->
    <el-dialog title="商家详情" v-model="viewOpen" width="1000px" append-to-body>
      <el-form ref="packageRef" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="商家名称" prop="merId">
<!--              <mer-select :key="refreshTime" v-model="form.merId" :typeList=[1,2]-->
<!--                          :disabledValue="1"></mer-select>-->
              {{ form.merName }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="套餐名称" prop="prodName">
              <el-input v-model="form.prodName" placeholder="请输入套餐名称" :disabled="true"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="主图" prop="prodMainPic">
              <image-preview :src="form.prodMainPic" :width="150" :height="150"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="详情图" prop="prodDetailPic" >
              <image-preview :src-list="form.prodDetailPic" :width="150" :height="150"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="有效期" prop="effTime">
                <span v-if="form.effTime>0">{{ form.effTime }}天 </span>
                <span v-else>长期有效</span>
              </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="销售时间" prop="saleStartTime">
              {{  parseTime(form.saleStartTime, '{y}-{m}-{d}')  }} - {{  parseTime(form.saleEndTime, '{y}-{m}-{d}')  }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="原价" prop="origPrice">
              <el-input-number v-model="form.origPrice" :max="999999" :min="0.01" :precision="2" :disabled="true"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="售价" prop="price" >
              <el-input-number v-model="form.price" :max="999999" :min="0.01" :disabled="true"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="限购次数" prop="limitTimes">
              <el-input-number v-model="form.limitTimes" :max="999999" :min="1" step-strictly :disabled="true"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="库存数量" prop="store">
              <el-input-number v-model="form.store" :max="999999" :min="1" step-strictly :disabled="true"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="适用人数" prop="maxPeoples">
              <el-input-number v-model="form.maxPeoples" :max="999999" :min="1" step-strictly :disabled="true"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="预约信息" prop="reserveInfo">
              {{ form.reserveInfo }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="使用时间" prop="serviceTime">
              {{ form.serviceTime }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="描述" prop="prodDesc">
              <editor v-model="form.prodDesc" :min-height="192" :readOnly="true"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="viewOpen = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup name="Tprod">
import {listTprod, getTprod, delTprod, addTprod, updateTprod} from "@/api/system/tprod";
import {getTmer} from "@/api/system/tmer";
import {watch, onBeforeUnmount, ref} from "vue";
import MerSelect from "@/components/MerSelect/index.vue";
import router from "@/router";
import useUserStore from "@/store/modules/user";
const userStore = useUserStore()
const {proxy} = getCurrentInstance();
const {
  t_is_yes,
  package_service_time,
  package_reserve_info,
  shop_type,
  ty_play_type,
  effective_time,
  sport_type,
  tprod_publish_type
} = proxy.useDict('t_is_yes', 'tprod_publish_type', 'package_service_time', 'package_reserve_info', 'shop_type', 'ty_play_type', 'effective_time', 'sport_type');

const tprodList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const saleTimeRange = ref([]);
const validTimeRange = ref([]);
const disableNum = ref(0);
const refreshTime = ref(0); //组件刷新次数
const viewOpen = ref(false);


const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    merId: undefined,
    prodName: undefined,
    prodDesc: undefined,
    prodCatalogId: undefined,
    type: 1,
    saleStartTime: undefined,
    saleEndTime: undefined,
    effTime: undefined,
    origPrice: undefined,
    effStartTime: undefined,
    effEndTime: undefined,
    reserveInfo: undefined,
    serviceTime: undefined,
    maxPeoples: undefined,
    isPublic: undefined,
    limitTimes: undefined,
    store: undefined,
    sold: undefined,
    isFree: undefined,
    price: undefined,
    cityCode: undefined,
    areaCode: undefined,
    areaPath: undefined,
    addr: undefined,
    addrDesc: undefined,
    status: undefined,
    publishStatus: undefined
  },
  rules: {
    merId: [
      {required: true, message: "商家名称不能为空", trigger: "blur"}
    ],
    prodName: [
      {required: true, message: "套餐名称不能为空", trigger: "blur"}
    ],
    price: [
      {required: true, message: "标准价格不能为空", trigger: "blur"}
    ],
    prodMainPic: [
      {required: true, message: "主图不能为空", trigger: "blur"}
    ],
    // prodDetailPic: [
    //   {required: true, message: "详情图不能为空", trigger: "blur"}
    // ],
    limitTimes: [
      {required: true, message: "限购人数不能为空", trigger: "blur"}
    ],
    saleStartTime: [
      {required: true, message: "销售时间不能为空", trigger: "blur"}
    ],
    // reserveInfo: [
    //   {required: true, message: "请选择是否需要预约", trigger: "blur"}
    // ],
    prodDesc: [
    {required: true, message: "描述不能为空", trigger: "blur"}
    , {validator: validateEditor, message: "描述不能为空", trigger: "blur"}
    ],
    store: [
      {required: true, message: "不能为空", trigger: "blur"},
      // {
      //   validator: (rule, value, callback) => {
      //     if (form.packageableType === 'Business') {
      //       callback();
      //     }
      //     if (value > editPersonNum.value) {
      //       if (editPersonNum.value > 0) {
      //         callback(new Error("人数不能大于人数" + editPersonNum.value));
      //       }
      //       callback();
      //
      //     } else {
      //       callback();
      //     }
      //   },
      //   trigger: "blur"
      // }
    ],
    validTime: [
      {required: true, message: "请选择活动时间", trigger: "blur"},
      {
        validator: checkValidTimeRange,
        trigger: 'change'
      }
    ],
    origPrice: [
      {required: true, message: "请填写原价", trigger: "blur"}
    ]
    // effTime: [
    //   {required: true, message: "请选择有效期", trigger: "blur"}
    // ]
  }
});

const {queryParams, form, rules} = toRefs(data);

/** 查询套餐列表列表 */
function getList() {
  loading.value = true;
  listTprod(queryParams.value).then(response => {
    tprodList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

function validateEditor(rule, value, callback) {
  if (value === null || value === undefined || value === '<p></p>' || value === '<p><br></p>') {
    callback(new Error('不能为空'));
  } else {
    callback();
  }
}
// 表单重置
function reset() {
  form.value = {
    prodId: undefined,
    merId: undefined,
    prodName: undefined,
    prodMainPic: undefined,
    prodDetailPic: undefined,
    prodDesc: undefined,
    chatPic: undefined,
    prodCatalogId: undefined,
    type: 1,
    saleStartTime: undefined,
    saleEndTime: undefined,
    effTime: undefined,
    effStartTime: undefined,
    effEndTime: undefined,
    reserveInfo: undefined,
    serviceTime: undefined,
    maxPeoples: undefined,
    isPublic: undefined,
    limitTimes: undefined,
    store: undefined,
    sold: undefined,
    isFree: undefined,
    price: undefined,
    cityCode: undefined,
    areaCode: undefined,
    areaPath: undefined,
    addr: undefined,
    addrDesc: undefined,
    longitude: 118.8083,
    latitude: 31.8639,
    sortNum: undefined,
    status: undefined,
    statusReason: undefined,
    auditTime: undefined,
    auditor: undefined,
    ext1: undefined,
    ext2: undefined,
    ext3: undefined,
    state: undefined,
    createTime: undefined,
    creator: undefined,
    modifyTime: undefined,
    modifier: undefined
  };
  proxy.resetForm("tprodRef");
  saleTimeRange.value = [];
  validTimeRange.value = [];
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  // ids.value = selection.map(item => item.prodId);
  // single.value = selection.length != 1;
  // multiple.value = !selection.length;
  ids.value = selection.map(item => item.prodId);
  single.value = selection.length != 1;
  let type = true
  if(selection.length == 1) {
    // 只选择一个
    if(selection[0].merStatus == '02' && selection[0].publishCount === 0) {
      type = false
    } else {
      type = true
    }
  }else {
    // 选择多个
    type = false
    if(selection.length == 0) {
      type = true
    }else {
      selection.map(item => {
        if(item.merStatus == '02' || item.publishCount === 0) {
          type = true
          return
        }
      })
    }
    
  }
  multiple.value = type
}

/** 新增按钮操作 */
function handleAdd() {
  disableNum.value = 0
  refreshTime.value += 1
  reset();
  open.value = true;
  title.value = "添加套餐";
  form._object.form.maxPeoples = 1
  form._object.form.reserveInfo = '无需预约'
  form._object.form.serviceTime = '营业时间内可用'
}

function changeReserveInfo() {
  if(form._object.form.reserveInfo == '') {
    form._object.form.reserveInfo = '无需预约'
  }
}

function changeServiceTime() {
  if(form._object.form.serviceTime == '') {
    form._object.form.serviceTime = '营业时间内可用'
  }
}

/** 修改按钮操作 */
function handleUpdate(row) {
  disableNum.value = 1
  reset();
  const _prodId = row.prodId || ids.value
  getTprod(_prodId).then(response => {
    form.value = response.data;
    saleTimeRange.value = [response.data.saleStartTime, response.data.saleEndTime];
    validTimeRange.value = [response.data.effStartTime, response.data.effEndTime];
    open.value = true;
    title.value = "修改套餐";
    refreshTime.value += 1
  });
}

/** 详细按钮操作 */
function handleView(row) {
  const _prodId = row.prodId || ids.value
  getTprod(_prodId).then(response => {
    refreshTime.value += 1
    if(response.data.prodDetailPic) {
      response.data.prodDetailPic = response.data.prodDetailPic.split(',')
    }
    form.value = response.data;
    viewOpen.value = true;
  });
}


/** 提交按钮 */
function submitForm() {
  // if(!form.value.effTime) {
  //   form.value.effTime = '长期'
  // }
  if(!form.value.maxPeoples) {
    form.value.maxPeoples = 1
  }
  if(form.value.origPrice <= form.value.price) {
    proxy.$modal.msgError('原价需要大于售价哦');
    return
  }
  if(form.value.prodDesc) {
    form.value.prodDesc = form.value.prodDesc.replace(/<img/g, '<img style="max-width: 100%;height: auto;"');
    form.value.prodDesc = form.value.prodDesc.replace('<iframe', `<video controls="" autoplay="" style="width: 100%;"`).replace('</iframe>', '</video>')
  }
  if (form.value.saleStartTime) {
    form.value.saleStartTime = form.value.saleStartTime + " 00:00";
  }
  if (form.value.saleEndTime) {
    form.value.saleEndTime = form.value.saleEndTime + " 00:00";
  }
  proxy.$refs["tprodRef"].validate(valid => {
    if (valid) {
      if (form.value.prodId != null) {
        updateTprod(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addTprod(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _prodIds = row.prodId || ids.value;
  proxy.$modal.confirm('是否确认删除套餐编号为"' + _prodIds + '"的数据项？').then(function () {
    return delTprod(_prodIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

// 定价
function handlePrice(row) {
  router.push('/system/tprice/index/' + row.prodId)
}

// 发布
function handlePublish(row) {
  router.push({
    path: "/system/tprodshop/index/" + row.prodId,
    query: {
      prodId: row.prodId,
      merId: row.merId
    }
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/tprod/export', {
    ...queryParams.value
  }, `tprod_${new Date().getTime()}.xlsx`)
}

function handleSaleTimeChange(value) {
  if (value && value.length === 2) {
    form.value.saleStartTime = value[0];
    form.value.saleEndTime = value[1];
  }
}

function checkValidTimeRange(rule, value, callback) {
  const saleEndTime = saleTimeRange.value ? saleTimeRange.value[1] : null;
  const effEndTime = validTimeRange.value ? validTimeRange.value[1] : null;
  if (saleEndTime && saleEndTime > effEndTime.value) {
    callback(new Error('报名结束时间不能大于活动结束时间:' + effEndTime.value));
  } else {
    callback();
  }
}

onActivated(() => {
  getList();
})

getList();

watch(()=>data.form.merId,(oldvalue,newvalue)=>{
  if(data.form.merId) {
    getTmer(data.form.merId).then(response => {
    saleTimeRange.value = [response.data.contStartTime, response.data.contEndTime];
    form.value.saleStartTime = response.data.contStartTime
    form.value.saleEndTime = response.data.contEndTime
    });
  }
})
</script>
